/*
 *  ufmail, a suite of mail servers
 *  Copyright (C) 2013  Jonathon Keogh
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 *  Jonathon Keogh e-mail: jdkeogh@live.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include "log.h"
#include "server-smtp-init.h"
#include "ufmail.h"

// TODO Handle Ctrl+C so that there is a graceful shut down
// TODO Also handle signals so that when kill sent it is done gracefully

int main(int argc, char *argv[]) {
	pid_t pidChild;
	pthread_t pThreads[_MAX_SOCK]; // TODO malloc etc.

	// Consider whether to use fork() here
	shOutputLogToConsole = 0;
	if(argc > 1 && strcmp(argv[1], "--no-fork") == 0) {
		// Do not fork
		pidChild = 0;
		shOutputLogToConsole = 1;
	} else {
		// OK to fork
		pidChild = fork();
	}

	printf("ufmail version 0.1, Copyright (C) 2013 Jonathon Keogh\n"); // TODO Take from config.h
    printf("ufmail comes with ABSOLUTELY NO WARRANTY; for details see COPYING\n");
    printf("This is free software, and you are welcome to redistribute it\n");
    printf("under certain conditions; see COPYING for details.");

	// Is this the parent or child?
	if(pidChild == 0) {
		// Child process
		// Try to open log file
		fLog = fopen("ufmail.log", "a");
		if(fLog == NULL) {
			// TODO Error
			fprintf(stderr, "Cannot open log file");
			exit(1);
		}

		// Starting up
		writeToLog(LOG_INFO, "Starting up.");

		// Init server sockets and PIDs
		iServerSocket = malloc(sizeof(int) * _MAX_SOCK);
		memset(iServerSocket, 0, sizeof(int) * _MAX_SOCK);

		// Start SMTP
		if(pthread_create(&pThreads[0], NULL, initServer_SMTP, (void *) NULL) != 0) {
			writeToLog(LOG_ERROR, "pthread_create did not succeed");
		}

		// TODO Wait - this needs to monitor the threads and exit when all are done
		while(1);
	} else if(pidChild < 0) {
		// Error
		writeToLog(LOG_ERROR, "fork() did not succeed");
		exit(1);
	}

	return 0;
}
